<?php

namespace App\Http\Controllers\User;

use App\Http\Requests\PermissionRequest;
use App\Models\Permission;
use Illuminate\Http\Request;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Input;


class PermissionController extends Controller
{
    public function index(){
        $rel = Permission::where('active','0')->get();
        $arr = $arr2 = '';
        for ( $i=$j=0;$i<count($rel);$i++ ){
            if($rel[$i]->parentmenu==0){
                $arr[] = $rel[$i];
            }else{
                $arr2[] = $rel[$i];
            }
        }
        for ( $i=0;$i<count($arr2);$i++ ) {
            for ( $j=0;$j<count($arr);$j++ ) {
                if ($arr[$j]->id == $arr2[$i]->parentmenu) {
                    array_splice($arr, $j+1,0,array($arr2[$i]));
                }
            }
        }
        return view('akl.admin.Nav_index')->with('permission',$arr);
    }

    public function getAdd(){
        $rel = Permission::where('active','0')->get();
        return view('akl.admin.Nav_add')->with('permission',$rel);
    }

    public function postAdd(PermissionRequest $request){
        $inp = array(
            'name' => $request->all()['model'].'/'.$request->all()['controller'].'/'.$request->all()['action'],
            'display_name' => $request->all()['display_name'],
            'active' => $request->all()['show'],
            'parentmenu' => $request->all()['parentmenu'],
        );
        $rel = Permission::create($inp);
        if($rel->wasRecentlyCreated) return back()->with('errors',"添加成功");
        return back()->with('errors',"添加失败，请重试");
    }

    public function destroy(Request $request,$id){
        $rel = Permission::where('id',$id)->update(array('active'=>'1'));
        if($rel) return back()->with('errors',"隐藏成功");
        return back()->with('errors',"隐藏失败，请重试");
    }

    public function edit($id){
        $permission = Permission::get();
        $one = Permission::find($id);
        $one->name = explode('/',$one->name);
        return view('akl.admin.Nav_edit',compact('permission','one'));
    }

    public function store(PermissionRequest $request){
        $rel = Input::all();
        $rels['name'] = $rel['model'].'/'.$rel['controller'].'/'.$rel['action'];
        $rels['display_name'] = $rel['display_name'];
        $rels['active'] = $rel['show'];
        $rels['parentmenu'] = $rel['parentmenu'];
        $rel = Permission::where('id',$rel['id'])->update($rels);
        if($rel) return back()->with('errors',"更新成功");
        return back()->with('errors',"更新失败，请重试");
    }



}
